package com.lst.projectlib.component.CustomView;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;

import java.util.List;

/**
 * Created by sxy on 2017/11/7.
 */

public class NoScrollViewPager extends ViewPager {
    private boolean noScroll = false;
    private List<Boolean> canScrollItem;

    public NoScrollViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    public NoScrollViewPager(Context context) {
        super(context);
    }

    public void setNoScroll(boolean noScroll) {
        this.noScroll = noScroll;
    }

    public void setCanScrollItem(List<Boolean> canScrollItem) {
        this.canScrollItem = canScrollItem;
    }

    @Override
    public void scrollTo(int x, int y) {
        super.scrollTo(x, y);
    }

    @Override
    public boolean onTouchEvent(MotionEvent arg0) {
        /* return false;//super.onTouchEvent(arg0); */
        switch (arg0.getAction()) {
        }
        return !noScroll && super.onTouchEvent(arg0);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent arg0) {
        return !noScroll && super.onInterceptTouchEvent(arg0);
    }

    private float beforeX;

    //-----禁止左滑-------左滑：上一次坐标 > 当前坐标
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (canScrollItem != null) {
            if (canScrollItem.get(getCurrentItem())) {
                return super.dispatchTouchEvent(ev);
            } else {
                switch (ev.getAction()) {
                    case MotionEvent.ACTION_DOWN://按下如果‘仅’作为‘上次坐标’，不妥，因为可能存在左滑，motionValue大于0的情况（来回滑，只要停止坐标在按下坐标的右边，左滑仍然能滑过去）
                        beforeX = ev.getX();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        float motionValue = ev.getX() - beforeX;
                        if (motionValue < 0) {//禁止右滑
                            return true;
                        }
                        beforeX = ev.getX();//手指移动时，再把当前的坐标作为下一次的‘上次坐标’，解决上述问题
                        break;
                    default:
                        break;
                }
            }
            return super.dispatchTouchEvent(ev);
        }else {
            return super.dispatchTouchEvent(ev);
        }
    }

    @Override
    public void setCurrentItem(int item, boolean smoothScroll) {
        super.setCurrentItem(item, smoothScroll);
    }

    @Override
    public void setCurrentItem(int item) {
        //false 去除滚动效果
        //super.setCurrentItem(item,false);
        super.setCurrentItem(item);
    }
}
